//[{"username":"jack","pwd":"123456","phone":"18672599132","email":"9132@qq.com"},{"username":"tony","pwd":"123456","phone":"18685239132","email":"123@qq.com"}]
var data = JSON.parse(localStorage.getItem('users'));
var bodys = document.body;
var table = document.createElement("table");
var users = localStorage.getItem('' +
    'users')?JSON.parse(localStorage.getItem('users')):[]
bodys.appendChild(table);
table.style.width="1080px";
// table.style.height="1000px";
table.style.margin="0 auto";
table.className = "table table-hover table-bordered table-striped";
function ayy(data){
    document.getElementsByTagName('table')[0].innerHTML = '';
    var thead = document.createElement("thead");
    table.appendChild(thead);

    //添加表头
    for(key in data[0]){
        var td = document.createElement("td");
        td.innerHTML=key;
        var a=thead.appendChild(td);
    }
    var tbody = document.createElement("tbody");
    table.appendChild(tbody);
    tbody.className="a";


    //添加内容
    for(var i=0;i<data.length;i++){
        var tr=document.createElement("tr");
        var s = tbody.appendChild(tr);
        tr.style.width="1080px";
        tr.style.height="30px";
        tr.style.border="1px solid black";
        for(var j in data[i]){
            var td =document.createElement("td");
            td.innerHTML = data[i][j];
            tr.appendChild(td);
        }
    }

    //追加全选
    var tables= document.getElementsByTagName("table")[0].firstElementChild.firstElementChild
    var tds =document.createElement("td");
    tds.innerHTML = '<input type="checkbox" class="a"/>全选';
    thead.insertBefore(tds,tables);
    tds.className="all";

    //追加操作
    var tables= document.getElementsByTagName("table")[0].firstElementChild.firstElementChild
    var tds1 =document.createElement("td");
    tds1.innerHTML = '操作';
    thead.appendChild(tds1);

    //追加单个input的框;
    var a=document.getElementsByTagName('tbody')[0].children;
    for(var j=0;j<a.length;j++){
        var trs= a[j].firstElementChild;
        var tdss =document.createElement("td");
        tdss.innerHTML = '<input type="checkbox"/>';
        a[j].insertBefore(tdss,trs);
        tdss.className="chb";
    }
    //追加删除和修改
    var a=document.querySelectorAll(".a tr");
    for(var j=0;j<a.length;j++){
        var trs= a[j].firstElementChild;
        var tdss1 =document.createElement("td");
        tdss1.innerHTML = '<button class="but1 btn btn-primary">修改</button><button class="but2 btn btn-warning" index="'+j+'">删除</button>';
        a[j].appendChild(tdss1);
    }

    //全选事件
    var all = document.querySelector("thead>td:first-child>input");
    // 找到table下面thead下第一个td中的input，为其绑定单击事件
    all.onclick= function(){
        var chb=document.querySelectorAll("table>tbody>tr>td:first-child>input");
        // 获取table下tbody下所有第一个td中的input
        for(var i= 0;i<chb.length;i++){
            // 遍历chb数组中每个chb
            chb[i].checked=this.checked;
            // 让每一个chb的状态都跟All得状态一样
        }
    }

    // 单个选中取消操作
    var chb=document.querySelectorAll("table>tbody>tr>td:first-child>input");
    // 找到table下tbody下的所有第一个td中的input 保存在chbs
    for(var i=0;i<chb.length;i++){
        // 遍历chb数组中每个chb
        chb[i].onclick=function(){
            // 为当前chb绑定单击事件
            if(!this.checked){
                // 如果当前chb未选中
                all.checked=false;
                // all修改为未选中
            }
            else{
                var unSel = document.querySelectorAll("table>tbody td:first-child>input:not(:checked)");
                // 获得table中tbody下所有第一个td中的未选中的input unSel
                if(unSel.length==0){
                    // 如果unSel的length是等于0
                    all.checked=true;
                    // all修改为选中
                }else{
                    all.checked=false;
                    // all修改为未选中
                }
            }
        }
    }

    //修改事件
    var but1= document.getElementsByClassName("but1");
    // console.log(but1);
    for(var j=0;j<but1.length;j++){
        but1[j].onclick = fun
    }

    //删除事件
    var but2 = document.getElementsByClassName("but2");
    for(var i = 0;i<but2.length;i++){
        but2[i].onclick = fun2;
    }
}

ayy(data)

function fun(){
    document.getElementsByClassName("box")[0].style.display = "block";
    var tr= this.parentNode.parentNode;
    var td = tr.getElementsByTagName("td");
    var input = document.getElementsByClassName("int");
    for (var i = 0;i < input.length;i++) {
        input[i].value = td[i+1].innerHTML;
    }
    //确定
    var box2 = document.getElementsByClassName("box2")[0];
    var index = this.parentNode.parentNode.rowIndex;
    box2.onclick = function(){
        document.getElementsByClassName("box")[0].style.display = "none";
        var td = tr.getElementsByTagName("td");
        var input = document.getElementsByClassName("int");
        for (var i = 0;i<input.length;i++){
            td[i+1].innerHTML = input[i].value;
        }
        var i=0;
        for(var j in data[index]){
            data[index][j]=td[i+1].innerHTML;
            localStorage.setItem('users',JSON.stringify(data))
            i++;
        }


    }
}
//清空
var box1 = document.getElementsByClassName("box1")[0];
box1.onclick =function(){
    var input = document.getElementsByClassName("int");
    for (var i = 0;i < input.length;i++) {
        input[i].value = "";
    }
}
//删除

function fun2(j){
    var tr= this.parentNode.parentNode;
    // console.log(tr);
    var a =document.getElementsByTagName("tbody")[0];
    // console.log(a);
    if(confirm("是否删除！")==true){
        a.removeChild(tr);
        data.splice(this.getAttribute('index'), 1)
        localStorage.setItem('users',JSON.stringify(data))
        console.log(data)
    }


}

// 取消
var box4 = document.getElementsByClassName("box4")[0];
box4.onclick = function(){
    document.getElementsByClassName("box")[0].style.display = "none";
}
//添加
var but1 = document.getElementsByClassName("but1")[0];
but1.onclick = function(){
    document.getElementsByClassName("box")[0].style.display = "block";
}

var input = document.getElementsByClassName("int");
var box3 = document.getElementsByClassName("box3")[0];
box3.onclick = function(){
    var obj = {};
    for(var i=0;i<input.length;i++){
        obj[i]=input[i].value;
    }
    var keyMap = {0:"username", 1: 'pwd',2:'phone',3:'email'};
    var objs= Object.keys(obj).reduce((newData, key) => {
        let newKey = keyMap[key] || key
        newData[newKey] = obj[key]
        return newData
    }, {})
    console.log(objs)
    data.push(objs)
    localStorage.setItem('users',JSON.stringify(data))
    ayy(data)

}

//全部删除（这个不建议使用）
//var but = document.getElementsByClassName("but")[0];
//but.onclick = function(){
//var bodys = document.body;
//var tables= document.getElementsByTagName("table")[0];
//console.log(tables);
//bodys.removeChild(tables);
//alert("确定全部删除！");
//}



//全部删除(全部删除用这个比较好，因为这个结合了前面的单选框)

var but = document.getElementsByClassName("but")[0];
but.onclick = function(){
    var b = confirm("是否删除!")
    var chb=document.querySelectorAll("table>tbody>tr>td:first-child>input");
    for(var i = 0;i<chb.length;i++){
        if(chb[i].checked==true){
            var tr = chb[i].parentNode.parentNode;
            console.log(tr)
            var a =document.getElementsByTagName("tbody")[0];
            if(b==true){
                a.removeChild(tr)
            }

        }

    }
}

// 查询
// input框
var phone = document.getElementsByClassName("phone")[0];
// console.log(phone);
var button = document.getElementsByClassName("button")[0];
// console.log(button);
button.onclick = function(){
    var arr = [];
    for(var i =0;i<data.length;i++){
        if(data[i]["phone"]==phone.value){
            arr.push(data[i]);
        }
    }
    ayy(arr);
}
//拖拽修改模态框
window.onload = function () {
    var oDiv = document.getElementById("div1");
    //可拖拽部分
    var oDiv2 = document.getElementById("div2");
    //鼠标按下事件
    oDiv2.onmousedown = function (ev) {
        var oEvent = ev || event;
        //获取当前位置
        var disX = oEvent.clientX-oDiv.offsetLeft;
        var disY = oEvent.clientY-oDiv.offsetTop;

        //创建一个拖拽留下的box方框
        var oBox = document.createElement('div');
        oBox.className = 'box5';
        oBox.style.width = oDiv.offsetWidth+'px';
        oBox.style.height = oDiv.offsetHeight+'px';
        oBox.style.left = oDiv.offsetLeft+'px';
        oBox.style.top = oDiv.offsetTop+'px';
        document.body.appendChild(oBox);//指明oBox加在哪
        //鼠标松开事件
        document.onmousemove = function(ev){
            var oEvent = ev || event;
            //获取当前的位置
            var pos = getPos(oEvent);
            var l= pos.x-disX;
            var t= pos.y-disY;
            //临界点时的操作
            if(l<0)     //更改临界值可实现磁性吸附
            {
                l=0;
            }
            else if(l>document.documentElement.clientWidth-oDiv.offsetWidth)
            {
                l=document.documentElement.clientWidth-oDiv.offsetWidth;
            }

            if(t<0)
            {
                t=0;
            }
            else if(t>document.documentElement.clientHeight-oDiv.offsetHeight)
            {
                t=document.documentElement.clientHeight-oDiv.offsetHeight;
            }

            oBox.style.left = l + 'px';
            oBox.style.top = t + 'px';
        };

        document.onmouseup = function (){
            oDiv.style.left = oBox.offsetLeft+'px';
            oDiv.style.top = oBox.offsetTop+'px';
            document.onmousemove = null;
            document.onmouseup = null;

            document.body.removeChild(oBox);
        };

        return false;

    };

};
//获取当前的位置
function getPos(ev){
    var scrollerTop = document.body.scrollTop || document.documentElement.scrollTop;
    var scrollerLeft = document.body.scrollLeft || document.documentElement.scrollLeft;

    return {x:ev.clientX+scrollerLeft,y:ev.clientY+scrollerTop};
}